// pages/upgrade/downloadFile/index.js
import gaiaManager from '../../../utils/gaiaManager.js'
import bluetoothManager from '../../../utils/bluetooth.js'

Page({
  data: {
    // 页面状态
    isLoading: true,
    showError: false,
    errorMessage: '',
    
    // 设备连接状态
    deviceConnected: false,
    
    // 文件信息和升级选项（从上一页传递）
    fileData: null,
    upgradeOptions: null,
    
    // 下载状态（与安卓版本DownloadStatus一致）
    downloadStatus: 'idle', // idle, downloading, completed, failed
    downloadProgress: 0,
    downloadMessage: '',
    
    // 文件内容信息
    fileContent: null,
    
    // 操作状态
    canStartUpgrade: false
  },

  onLoad(options) {
    console.log('文件下载页面加载:', options)
    
    // 解析传递的参数
    if (options.file) {
      try {
        const fileData = JSON.parse(decodeURIComponent(options.file))
        this.setData({ fileData })
        console.log('文件数据:', fileData)
      } catch (error) {
        console.error('解析文件数据失败:', error)
        this.showError('Invalid file data')
        return
      }
    }
    
    if (options.options) {
      try {
        const upgradeOptions = JSON.parse(decodeURIComponent(options.options))
        this.setData({ upgradeOptions })
        console.log('升级选项:', upgradeOptions)
      } catch (error) {
        console.error('解析升级选项失败:', error)
        this.showError('Invalid upgrade options')
        return
      }
    }
    
    this.initPage()
  },

  onShow() {
    this.loadFileContent()
  },

  // 初始化页面
  initPage() {
    this.setData({
      isLoading: true,
      showError: false,
      errorMessage: '',
      downloadStatus: 'idle',
      downloadProgress: 0,
      downloadMessage: '',
      fileContent: null,
      canStartUpgrade: false
    })
  },

  // 加载文件内容（与安卓版本DownloadFileFragment保持一致）
  async loadFileContent() {
    try {
      this.setData({ isLoading: true })
      
      // 检查设备连接状态
      if (!bluetoothManager.isConnected) {
        this.showError('Device not connected')
        return
      }
      
      this.setData({ deviceConnected: true })
      
      // 显示文件内容信息
      this.setFileContent()
      
    } catch (error) {
      console.error('加载文件内容失败:', error)
      this.showError('Failed to load file content: ' + error.message)
    } finally {
      this.setData({ isLoading: false })
    }
  },

  // 设置文件内容信息（与安卓版本FileContent一致）
  setFileContent() {
    if (!this.data.fileData) {
      return
    }
    
    const fileContent = {
      name: this.data.fileData.name,
      version: this.data.fileData.version,
      size: this.data.fileData.size,
      description: this.data.fileData.description,
      tags: this.data.fileData.tags || []
    }
    
    this.setData({ fileContent })
  },

  // 开始下载文件（与安卓版本downloadFile()一致）
  async startDownload() {
    try {
      console.log('开始下载文件:', this.data.fileData)
      
      this.setData({
        downloadStatus: 'downloading',
        downloadProgress: 0,
        downloadMessage: 'Initializing download...'
      })
      
      // 调用下载服务
      const response = await gaiaManager.downloadFile(this.data.fileData)
      
      if (response.success) {
        // 模拟下载进度
        this.simulateDownloadProgress()
      } else {
        this.setData({
          downloadStatus: 'failed',
          downloadMessage: 'Download failed: ' + response.error
        })
      }
      
    } catch (error) {
      console.error('下载文件失败:', error)
      this.setData({
        downloadStatus: 'failed',
        downloadMessage: 'Download failed: ' + error.message
      })
    }
  },

  // 模拟下载进度
  simulateDownloadProgress() {
    let progress = 0
    const interval = setInterval(() => {
      progress += Math.random() * 10
      if (progress >= 100) {
        progress = 100
        clearInterval(interval)
        
        this.setData({
          downloadStatus: 'completed',
          downloadProgress: 100,
          downloadMessage: 'Download completed successfully',
          canStartUpgrade: true
        })
      } else {
        this.setData({
          downloadProgress: Math.round(progress),
          downloadMessage: `Downloading... ${Math.round(progress)}%`
        })
      }
    }, 200)
  },

  // 取消下载（与安卓版本cancelDownload()一致）
  cancelDownload() {
    console.log('取消下载')
    
    this.setData({
      downloadStatus: 'idle',
      downloadProgress: 0,
      downloadMessage: '',
      canStartUpgrade: false
    })
    
    // 调用取消下载服务
    gaiaManager.cancelDownload()
  },

  // 开始升级（与安卓版本onClick()一致）
  async startUpgrade() {
    try {
      console.log('开始升级:', this.data.fileData)
      
      if (!this.data.canStartUpgrade) {
        wx.showToast({
          title: 'Please download the file first',
          icon: 'none'
        })
        return
      }
      
      // 调用升级服务
      const response = await gaiaManager.startUpgrade(this.data.fileData, this.data.upgradeOptions)
      
      if (response.success) {
        // 导航到升级进度页面
        wx.navigateTo({
          url: '/pages/upgrade/progress/index'
        })
      } else {
        wx.showToast({
          title: 'Upgrade failed: ' + response.error,
          icon: 'error'
        })
      }
      
    } catch (error) {
      console.error('开始升级失败:', error)
      wx.showToast({
        title: 'Upgrade failed: ' + error.message,
        icon: 'error'
      })
    }
  },

  // 重试下载
  retryDownload() {
    console.log('重试下载')
    this.startDownload()
  },

  // 显示错误
  showError(message) {
    this.setData({
      showError: true,
      errorMessage: message,
      isLoading: false
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadFileContent().finally(() => {
      wx.stopPullDownRefresh()
    })
  }
})